package com.oriole.api.module.sys.service.impl;

import com.oriole.api.module.sys.repository.SysUserRepository;
import com.oriole.api.module.sys.service.ISysUserService;
import com.oriole.common.constant.ValidEnum;
import com.oriole.entity.sys.SysUser;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author hautxxxyzjk@163.com
 * @since 2020-03-10
 */
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Resource
    private SysUserRepository sysUserRepository;

    @Override
    @Transactional(rollbackOn = {Exception.class})
    public SysUser save(SysUser sysUser) {
        return sysUserRepository.save(sysUser);
    }

    @Override
    @Transactional(rollbackOn = {Exception.class})
    public void deleteById(Long id) {
        sysUserRepository.deleteById(id);
    }

    @Override
    @Transactional(rollbackOn = {Exception.class})
    public void deleteBatchByIds(List<Long> ids) {
        ids.forEach(id -> {
            sysUserRepository.deleteById(id);
        });
    }

    @Override
    public List<SysUser> findAll() {
        return sysUserRepository.findAll();
    }

    @Override
    public Page<SysUser> findPage(Map<String, Object> condition, Pageable pageable) {
        if (null != condition && !condition.isEmpty()) {
            SysUser sysUser = new SysUser();
            if (condition.containsKey("username")) {
                sysUser.setUsername(condition.get("username").toString());
            }
            if (condition.containsKey("isSuper")) {
                String isSuper = condition.get("isSuper").toString();
                sysUser.setIsSuper(ValidEnum.valueOf(isSuper));
            }
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("isSuper", ExampleMatcher.GenericPropertyMatchers.exact());
            Example<SysUser> example = Example.of(sysUser, matcher);
            return sysUserRepository.findAll(example, pageable);
        }
        return sysUserRepository.findAll(pageable);
    }

    @Override
    public SysUser findByUsername(String username) {
        return sysUserRepository.findByUsername(username);
    }

    @Override
    public SysUser findById(Long id) {
        return sysUserRepository.findById(id).orElse(new SysUser());
    }
}
